package com.time.workbench.efficient.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.time.workbench.efficient.entity.bo.Application;
import com.time.workbench.efficient.entity.bo.ApplicationServer;
import com.time.workbench.efficient.entity.bo.Environment;
import com.time.workbench.efficient.entity.bo.Server;
import com.time.workbench.efficient.entity.dto.ApplicationPageReq;
import com.time.workbench.efficient.entity.vo.GitCommitVO;
import com.time.workbench.efficient.enums.EnvironmentCodeEnums;
import com.time.workbench.efficient.mapper.ApplicationMapper;
import com.time.workbench.efficient.util.GItAbstractUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 应用管理service
 */
@Service
@RequiredArgsConstructor
public class ApplicationService extends ServiceImpl<ApplicationMapper, Application> implements IService<Application> {

    private final ApplicationServerService applicationServerService;

    private final EnvironmentService environmentService;

    private final ServerService serverService;

    public Page<Application> page(ApplicationPageReq applicationPageReq) {
        IPage<Application> applicationPage = new Page<>(applicationPageReq.getCurrent(), applicationPageReq.getPageSize());
        return baseMapper.pageApplication(applicationPage, applicationPageReq);
    }

    public List<String> listBranch(String id) {
        Application application = getById(id);
        GItAbstractUtil git = GItAbstractUtil.getGit(application.getGitAddress());
        return git.branchAll();
    }

    public List<GitCommitVO> listCommit(String id, String branch) {
        Application application = getById(id);
        GItAbstractUtil git = GItAbstractUtil.getGit(application.getGitAddress());
        return git.commitAll(branch);
    }

    public List<Server> getServerByApplicationId(Integer applicationId, EnvironmentCodeEnums environmentCodeEnums) {
        Environment environment = environmentService.getEnvironmentByCode(environmentCodeEnums);
        List<ApplicationServer> applicationServer = applicationServerService.getApplicationServer(applicationId, environment.getId());
        if (CollectionUtil.isEmpty(applicationServer)) {
            return new ArrayList<>();
        }
        return serverService.listByIds(applicationServer.stream().map(ApplicationServer::getServerId).collect(Collectors.toList()));

    }
}
